//
//  AREditUserInfoController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/18.
//

import UIKit
import Photos
import Kingfisher
import DatePickerDialog
import CountryPickerView

/// 编辑用户信息
class AREditUserInfoController: ARBaseViewController {

    // MARK: - Proprety
    
    // private
    
    private let viewModel = AREditUserInfoViewModel()
    private let countryPicker = CountryPickerView()
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        updateValue()
    }
    
    // MARK: - UI

    private func setupUI() {
        
        // nav
        self.ar_setupNavBgImg()
        self.ar_configWhiteBackItem()
        self.title = ARHelper.localString("Edit profile")
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: ARHelper.font(18, weight: .medium)]
        }
        
        let takePhotoImgView = UIImageView(image: .init(named: "mine_takePhoto_icon"))
        
        self.view.addSubview(avatarBtn)
        self.view.addSubview(takePhotoImgView)
        self.view.addSubview(nicknameOperationView)
        self.view.addSubview(birthdayOperationView)
        self.view.addSubview(countryOperationView)
        self.view.addSubview(sendBtn)
        
        avatarBtn.snp.makeConstraints { make in
            make.width.height.equalTo(100)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(68)
        }
        
        takePhotoImgView.snp.makeConstraints { make in
            make.width.height.equalTo(26)
            make.right.equalTo(avatarBtn).offset(-10)
            make.bottom.equalTo(avatarBtn)
        }
        
        nicknameOperationView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
            make.height.equalTo(44)
            make.top.equalTo(avatarBtn.snp.bottom).offset(28)
        }
        
        birthdayOperationView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
            make.height.equalTo(44)
            make.top.equalTo(nicknameOperationView.snp.bottom).offset(24)
        }
        
        countryOperationView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
            make.height.equalTo(44)
            make.top.equalTo(birthdayOperationView.snp.bottom).offset(24)
        }
        
        sendBtn.snp.makeConstraints { make in
            make.left.right.equalTo(nicknameOperationView)
            make.height.equalTo(48)
            make.bottom.equalToSuperview().offset(-84 - ARHelper.safeBottomHeight())
        }
    }
    
    // MARK: - Action
    
    @objc private func avatarBtnClicked(_ sender: UIButton) {
        
        ARLogManager.logPage(.editavatar)
        
        selectPhoto()
    }
    
    @objc private func birthdayOperationViewClicked(_ sender: UIButton) {
        birthdayDatePicker()
    }
    @objc private func nicknameOperationViewClicked(_ sender: UIButton) {
        ARKeyboardInputController.showKeyboardInput(at: self) { [weak self] str in
            if str.isEmpty {
                return
            }
            self?.viewModel.updateNickname(str)
            self?.updateValue()
        }
    }
    @objc private func countryOperationViewClicked(_ sender: UIButton) {
        pickCountry()
    }
    
    @objc private func doneBtnClicked(_ sender: UIButton) {
        self.ar.showLoading()
        viewModel.updateInfoToRemote { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            self?.ar.makeToast(ARHelper.localString("Edit successfully"))
            self?.updateValue()
        }
    }
    
    // MARK: Function
    
    private func birthdayDatePicker() {
        
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "yyyy-MM-dd"
        // 最少18岁
        let defaultDate = dateFormat.date(from: viewModel.birthday) ?? Date()
        
        DatePickerDialog().show(ARHelper.localString("Date of Birth"), doneButtonTitle: ARHelper.localString("Done"), defaultDate: defaultDate, datePickerMode: .date) { [weak self] date in
            guard let date = date else {
                return
            }
            
            // 判断时间
            if self?.judge18years(date) ?? false {
                let str = dateFormat.string(from: date)
                self?.viewModel.updateBirthday(str)
                self?.updateValue()
            } else {
                self?.ar.makeToast(ARHelper.localString("Must be at least 18 years old"))
            }
        }
    }
    
    private func pickCountry() {
        let picker = countryPicker
        picker.showPhoneCodeInView = false
        picker.delegate = self
        picker.dataSource = self
        picker.showCountriesList(from: self)
    }
    
    /// 判断是否年满18
    private func judge18years(_ date: Date) -> Bool {
        let calendar = Calendar.current
        let now = Date()

        let ageComponents = calendar.dateComponents([.year, .month, .day], from: date, to: now)
        if let ageYears = ageComponents.year, let ageMonths = ageComponents.month, let ageDays = ageComponents.day {
            if ageYears > 18 {
                 return true
            } else if ageYears == 18 {
                if ageMonths > 0 || (ageMonths == 0 && ageDays >= 0) {
                    return true
                } else {
                    return false
                }
            } else {
                return false
            }
        }
        return false
    }
    
    // MARK: Update value
    
    private func updateValue() {
        if let url = URL(string: viewModel.avatarUrl) {
            avatarBtn.kf.setImage(with: url, for: .normal)
        }
        
        nicknameOperationView.rightLabel.text = viewModel.nickname
        birthdayOperationView.rightLabel.text = viewModel.birthday
        countryOperationView.rightLabel.text = viewModel.country
        
        doneBtnEnable()
    }
    
    private func doneBtnEnable() {
        sendBtn.isEnabled = viewModel.valueDidChange()
    }
    
    // MARK: - Lazy
    
    private lazy var avatarBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(avatarBtnClicked(_:)), for: .touchUpInside)
        btn.layer.cornerRadius = 50
        btn.layer.masksToBounds = true
        return btn
    }()
    
    private lazy var nicknameOperationView: AREditUserInfoOperationView = {
        let btn = AREditUserInfoOperationView(type: .custom)
        btn.leftLabel.text = ARHelper.localString("Nick Name")
        btn.addTarget(self, action: #selector(nicknameOperationViewClicked(_:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var birthdayOperationView: AREditUserInfoOperationView = {
        let btn = AREditUserInfoOperationView(type: .custom)
        btn.leftLabel.text = ARHelper.localString("Date of Birth")
        btn.addTarget(self, action: #selector(birthdayOperationViewClicked(_:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var countryOperationView: AREditUserInfoOperationView = {
        let btn = AREditUserInfoOperationView(type: .custom)
        btn.leftLabel.text = ARHelper.localString("Country")
        btn.addTarget(self, action: #selector(countryOperationViewClicked(_:)), for: .touchUpInside)
        btn.updateArrowHidden(false)
        return btn
    }()
    
    private lazy var sendBtn: UIButton = {
        let btn = UIButton.ar.themeStyleButton()
        btn.addTarget(self, action: #selector(doneBtnClicked(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Submit"), for: .normal)
        return btn
    }()

}

/// Select photo
extension AREditUserInfoController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    fileprivate func selectPhoto() {
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let photoLibraryAction = UIAlertAction(title: "Choose from Photo Library", style: .default) { [weak self] _ in
            self?._selectPhotoFromLibrary()
        }
        let cameraAction = UIAlertAction(title: "Take Photo", style: .default) { [weak self] _ in
            self?._takePhoto()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
        alertController.addAction(cameraAction)
        alertController.addAction(photoLibraryAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    private func _takePhoto() {
        
        func takePhoto() {
            DispatchQueue.main.async {
                let imagePicker = UIImagePickerController()
                imagePicker.delegate = self
                imagePicker.sourceType = .camera
                imagePicker.cameraCaptureMode = .photo
                self.present(imagePicker, animated: true)
            }
        }
        
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        switch authStatus {
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { [weak self] author in
                if author {
                    takePhoto()
                    return
                }
                self?.ar.makeToast(ARHelper.localString("No permission"))
            }
        case .restricted, .denied:
            self.ar.makeToast(ARHelper.localString("No permission"))
        case .authorized:
            takePhoto()
        @unknown default:
            self.ar.makeToast(ARHelper.localString("No permission"))
        }
    }
    
    private func _selectPhotoFromLibrary() {
        // 权限
        getPHPhotoLibraryAuthorized { [weak self] isHaveAuthorizes, authorizeStatus in
            if isHaveAuthorizes == false {
                self?.ar.makeToast(ARHelper.localString("No permission"))
                return
            }
            
            DispatchQueue.main.async {
                self?._selectPhoto()
            }
        }
    }
    
    private func _selectPhoto() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        present(imagePicker, animated: true)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            // 在这里，你可以使用 selectedImage
            // 保存到本地
            if let data = selectedImage.jpegData(compressionQuality: 0.6) {
                self.ar.showLoading()
                self.viewModel.updateAvatar(data) { [weak self] err in
                    self?.ar.hideHUD()
                    if let err = err {
                        self?.ar.makeToast(err.localizedDescription)
                        return
                    }
                    // TODO: 刷新
                    self?.updateValue()
                }
            } else {
                // 失败
                self.ar.makeToast(ARHelper.localString("Failed to select image"))
            }
        }
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: Helper
    
    private func getPHPhotoLibraryAuthorized(resultClosure: @escaping ((_ isHaveAuthorizes: Bool, _ authorizeStatus: PHAuthorizationStatus) -> Void)) {
        let authorized = PHPhotoLibrary.authorizationStatus()
        if authorized == .notDetermined {
            PHPhotoLibrary.requestAuthorization { status in
                if status == .authorized {
                    resultClosure(true, status)
                } else {
                    resultClosure(false, status)
                }
            }
        } else if authorized == .denied || authorized == .restricted {
            resultClosure(false, authorized)
        } else {
            // authorized
            resultClosure(true, authorized)
        }
    }
}

extension AREditUserInfoController: CountryPickerViewDelegate {
    func countryPickerView(_ countryPickerView: CountryPickerView, didSelectCountry country: Country) {
        
        if country.code == "CN" {
            // 不能选择中国
            self.ar.makeToast("Cannot select China")
            return
        }
        
        self.viewModel.updateCountry(country.name)
        self.updateValue()
    }
    
    func countryPickerView(_ countryPickerView: CountryPickerView, willShow viewController: CountryPickerViewController) {
        viewController.tableView.contentInsetAdjustmentBehavior = .automatic
    }
    
}

extension AREditUserInfoController: CountryPickerViewDataSource {

    func navigationTitle(in countryPickerView: CountryPickerView) -> String? {
        return ARHelper.localString("Select a Country")
    }
    
    func searchBarPosition(in countryPickerView: CountryPickerView) -> SearchBarPosition {
//        if countryPickerView.tag == cpvMain.tag {
//            switch searchBarPosition.selectedSegmentIndex {
//            case 0: return .tableViewHeader
//            case 1: return .navigationBar
//            default: return .hidden
//            }
//        }
        return .tableViewHeader
    }
    
}
